package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.ProductConditionAdapter;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.bean.ListGoods;
import com.epfresh.bean.ProductCondition;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.GoodsListView;
import com.epfresh.views.dialog.BaseDialogView;
import com.epfresh.views.dialog.OnFilterClickListener;
import com.epfresh.views.dialog.ProductCategoryDialog;
import com.epfresh.views.dialog.ProductConditionDialog;

import java.util.ArrayList;
import java.util.List;


public class GoodsListActivity extends BaseActivity {

    private GoodsListView goodsListView;

    private TextView tvCategory;
    private TextView tvVolume;
    private TextView tvTime;
    private ImageView ivTime;
    private ImageView ivVolume;
    private View vTime;
    private View vCategory;
    private View vVolume;
    private View vFilterMain;

    private GoodsParameters parameters;
    private List<ListGoods> list;

//    private View vSearch;


//    private TextView tvSearch;
//    private TextView tvContent;


    private String title;
    private String sortProperty;
    int typeView;
    int isRecommended;
    String type;
    String categoryId;
    String categoryNameId;
    private int selectColor;

    @Override
    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.merchant_search_result, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);
        this.toolbarTitle = (TextView) actionbar.findViewById(R.id.toolbar_title);

        this.ivBack = (ImageView) actionbar.findViewById(R.id.iv_back);

        this.ivBack.setOnClickListener(this);
        return actionbar;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);

        if (savedInstanceState != null) {
            getIntent().putExtra("isRecommended", savedInstanceState.getInt("isRecommended", -1));
            getIntent().putExtra("type_view", savedInstanceState.getInt("type_view", 1));
            getIntent().putExtra("title", savedInstanceState.getString("title"));
            getIntent().putExtra("type", savedInstanceState.getString("type"));
            getIntent().putExtra("categoryId", savedInstanceState.getString("categoryId"));
            getIntent().putExtra("categoryNamesId", savedInstanceState.getString("categoryNamesId"));
            getIntent().putExtra("sortDirection", savedInstanceState.getBoolean("sortDirection"));
            getIntent().putExtra("storeId", savedInstanceState.getBoolean("storeId"));
        }

        init();

    }

    public void init() {
        selectColor = getResources().getColor(R.color.green_little);
//        vSearch = findViewById(R.id.ll_search);
//        tvSearch = (TextView) findViewById(R.id.tv_search);
//        tvContent = (TextView) findViewById(R.id.et_content);
//        tvSearch.setOnClickListener(this);

        ivBack.setVisibility(View.VISIBLE);
        vFilterMain = findViewById(R.id.ll_filter);
        if(getIntent().getStringExtra("storeId")!=null&&!"".equals(getIntent().getStringExtra("storeId")))
            vFilterMain.setVisibility(View.GONE);
        goodsListView = (GoodsListView) findViewById(R.id.fragment_ptr_home_ptr_frame);
        tvCategory = (TextView) findViewById(R.id.tv_latest);
        tvVolume = (TextView) findViewById(R.id.tv_volume);
        tvTime = (TextView) findViewById(R.id.tv_filter);
        ivTime = (ImageView) findViewById(R.id.iv_filter);
        ivVolume = (ImageView) findViewById(R.id.iv_volume);
        vTime = findViewById(R.id.ll_time);
        vCategory = findViewById(R.id.ll_category);
        vVolume = findViewById(R.id.ll_volume);


        vVolume.setOnClickListener(this);
        vTime.setOnClickListener(this);
        vCategory.setOnClickListener(this);

        vCategory.setVisibility(View.GONE);
        initSortStatus();
//        tvCategory.setOnClickListener(this);
//        tvCategory.setTextColor(selectColor);
//        tvTime.setTextColor(selectColor);
        tvCategory.setTextColor(selectColor);
        String title = getIntent().getStringExtra("title");

        isRecommended = getIntent().getIntExtra("isRecommended", -1);
        type = getIntent().getStringExtra("type");

        typeView = getIntent().getIntExtra("type_view", 1);
        parameters = new GoodsParameters();
        parameters.setStoreId(getIntent().getStringExtra("storeId"));
        if (isRecommended == 1) {
            parameters.setRecommended(true);
        } else if (isRecommended == 2) {
            parameters.setRecommended(false);
        } else {
            parameters.setRecommended(null);
        }

//        parameters.setSortProperty("isRecommended");
        parameters.setSortProperty("modifiedTime");
        parameters.setSortDirection("DESC");
        if ("1".equals(type) || "2".equals(type)) {
            List<String> types = new ArrayList<>();
            types.add(type);
            parameters.setTypes(types);
        }
        if (typeView == 1) {
//            tvSearch.setVisibility(View.GONE);
//            vSearch.setVisibility(View.GONE);
            vFilterMain.setVisibility(View.GONE);
//            toolbarTitle.setText(title);
            //parameters.setSortProperty("isRecommended");修改精品推荐的排序属性，不更改就好
            parameters.setSortProperty("modifiedTime");
        } else if (typeView == 2) {
//            toolbarTitle.setVisibility(View.GONE);
//            vSearch.setOnClickListener(this);
            parameters.setTitle(title);
//            tvContent.setText(title);
            this.title = title;
        } else if (typeView == 3) {
            categoryId = getIntent().getStringExtra("categoryId");
            categoryNameId = getIntent().getStringExtra("categoryNamesId");
            if ((categoryId != null && !"".equals(categoryId)) || (categoryNameId != null && !"".equals(categoryNameId))) {
                parameters.setCategoryId(categoryId);
//                tvContent.setText(title);
                if (categoryNameId != null && !"".equals(categoryNameId)) {
                    parameters.setNameId(categoryNameId);
                }
//                vSearch.setOnClickListener(this);
            } else {
                finish();
            }
        }


        goodsListView.setBaseActivity(this);
        list = goodsListView.getList();


        goodsListView.setParameters(parameters);
        goodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (goodsListView.getList().size() > i) {
                    Intent intent = new Intent(GoodsListActivity.this, DetailGoodsActivity.class);
                    intent.putExtra("id", goodsListView.getList().get(i).getId());
                    intent.putExtra("storeId",goodsListView.getList().get(i).getStoreId());
                    intent.putExtra("promotionItemId", goodsListView.getList().get(i).getPromotionItemId());
                    startActivity(intent);
                }
            }
        });

        boolean sortDirection = getIntent().getBooleanExtra("sortDirection", true);
        if(!sortDirection){
            parameters.setSortProperty(null);
            parameters.setSortDirection(null);
        }
        loadData();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putInt("isRecommended", isRecommended);
        outState.putInt("type_view", typeView);
        outState.putString("title", title);
        outState.putString("type", type);
        outState.putString("categoryId", categoryId);
        outState.putString("storeId", getIntent().getStringExtra("storeId"));
        outState.putString("categoryNamesId", categoryNameId);
        outState.putBoolean("sortDirection", getIntent().getBooleanExtra("sortDirection",true));
        super.onSaveInstanceState(outState);
    }

    OnFilterClickListener onFilterClickListener = new OnFilterClickListener() {
        @Override
        public void onFilter(GoodsParameters parameters) {
            String name = parameters.getName();
            if (name != null && !"".equals(name))
                tvCategory.setText(name);
            parameters.setSortProperty(sortProperty);
            parameters.setStoreId(getIntent().getStringExtra("storeId"));
            GoodsListActivity.this.parameters = parameters;
            goodsListView.setParameters(parameters);
            goodsListView.reload();

        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_time:
//                updateSort(v, tvTime, ivTime);
//                sort("modifiedTime");
                ivTime.setImageResource(R.mipmap.top_arrow);
                openSortDialog(1);//排序
                break;
            case R.id.ll_category:
                openProductCategory(null, parameters, onFilterClickListener);
                break;
            case R.id.ll_volume://筛选
//                updateSort(v, tvVolume, ivVolume);
//                sort("salesQuantity");
                ivVolume.setImageResource(R.mipmap.top_arrow);
                openSortDialog(2);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
            case R.id.ll_search:
                search();
                break;
        }
    }

    public void initSortStatus() {
        //ASC 顺序，DESC 倒序,true,表示顺序,
        vVolume.setTag(R.id.item_key_status, true);
        vTime.setTag(R.id.item_key_status, true);
        tvVolume.setTextColor(Color.parseColor("#626262"));
        tvTime.setTextColor(Color.parseColor("#626262"));
        ivVolume.setImageResource(R.mipmap.bottom_arrow);
        ivTime.setImageResource(R.mipmap.bottom_arrow);
    }

    public void updateSort(View v, TextView tv, ImageView iv) {
        Object tag = v.getTag(R.id.item_key_status);
        initSortStatus();
        boolean isAsc = false;
        if (tag != null && tag instanceof Boolean) {
            if (!((boolean) tag)) {
                isAsc = true;
            }
        }
        v.setTag(R.id.item_key_status, isAsc);
        tv.setTextColor(selectColor);
        if (isAsc) {
            parameters.setSortDirection("ASC");
            iv.setImageResource(R.mipmap.top_arrow);
        } else {
            parameters.setSortDirection("DESC");
            iv.setImageResource(R.mipmap.bottom_arrow);
        }

    }


    private void search() {

        Intent intent;
        if(getIntent().getStringExtra("storeId")!=null&&!"".equals(getIntent().getStringExtra("storeId")))
            intent = new Intent(this, SearchByStoreActivity.class);
        else
            intent = new Intent(this, SearchActivity.class);
        startActivity(intent);
        finish();
    }

    public void sort(String sortMode) {
        if (this.parameters == null)
            this.parameters = new GoodsParameters();
        this.sortProperty = sortMode;

        parameters.setSortProperty(sortMode);
        goodsListView.setParameters(parameters);
        goodsListView.reload();
    }

    private void loadData() {
        goodsListView.refresh();
    }


    ProductCategoryDialog productCategoryDialog;

    public void openProductCategory(String marketId, GoodsParameters parameters, OnFilterClickListener onFilterClickListener) {

        if (productCategoryDialog == null) {
            productCategoryDialog = new ProductCategoryDialog(this);
        }
        productCategoryDialog.setMarketId(marketId);
        productCategoryDialog.setParameters(parameters);
        productCategoryDialog.setOnFilterClickListener(onFilterClickListener);
        productCategoryDialog.show();
        productCategoryDialog.updateCategory();
    }


    @Override
    public void onBackPressed() {

        if (productCategoryDialog != null && productCategoryDialog.isShowing()) {
            productCategoryDialog.dismiss();
            return;
        }

        super.onBackPressed();
    }
    public void reSortStatus() {

//        tvVolume.setTextColor(Color.parseColor("#626262"));
//        tvTime.setTextColor(selectColor);
        ivVolume.setImageResource(R.mipmap.bottom_arrow);
        ivTime.setImageResource(R.mipmap.bottom_arrow);
    }
    public void reload() {

        goodsListView.setParameters(parameters);
        goodsListView.reload();
    }

    ProductConditionDialog popSort;
    ProductConditionAdapter sortAdapter;
    List<ProductCondition> listSort = new ArrayList<>();

    public void openSortDialog(int type) {
        if (popSort == null) {
            popSort = new ProductConditionDialog(this);
            popSort.resultTop();
            GridView gv = (GridView) popSort.findViewById(R.id.gv_more);
            sortAdapter = new ProductConditionAdapter(this, listSort);

            sortAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String filterCode = parameters.getFilterCode();
                    if (filterCode != null && !"".equals(filterCode)){
                        tvVolume.setTextColor(selectColor);
                        tvVolume.setText(parameters.getFilterName());

                    }else{
                        tvVolume.setTextColor(Color.parseColor("#626262"));
                        tvVolume.setText("筛选");
                    }
                    String sortName = parameters.getSortName();
                    if (sortName != null && !"排序".equals(sortName)){
                        tvTime.setTextColor(selectColor);
                    }
                    tvTime.setText(sortName);
                    reload();
                    popSort.dismiss();
                }
            });
            gv.setAdapter(sortAdapter);

            popSort.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    reSortStatus();
                }
            });

        }

        if (popSort.isShowing()) {
            popSort.dismiss();
        } else {
            popSort.hideContent();
            listSort.clear();
            if (type == 1) {//排序
                if ("排序".equals(tvTime.getText())){

                    listSort.addAll(sortAdapter.getSortCondition(true));
                }else {
                    listSort.addAll(sortAdapter.getSortCondition(false));

                }
            } else if (type == 2) {//筛选
                listSort.addAll(sortAdapter.getFilterCondition(true,goodsListView.getTagList()));
                if (listSort.isEmpty()){
                    popSort.showEmpty();
                }
            }

            sortAdapter.initParameters(parameters, type);
            popSort.show();
            sortAdapter.notifyDataSetChanged();
        }
    }
}
